<script setup>
import { reactive, ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { classList } from '@/enums'
import { updateNews, orderNews, getNewsList, newsIssueTemplate } from '@/api/news'
import { newsPublishApi } from '@/api/upload'
import Upload from '@/components/Upload.vue'
import { useUserInfo } from '@/stores/userinfo'

const { user } = useUserInfo()

const router = useRouter()
// 步骤状态，1表示当前在第1步，2表示第2步
const currentStep = ref(1)

// 新闻数据
const newsList = ref([])
// 分组新闻列表
const groupedNewsList = ref([])

// 组件挂载时从API获取待发布新闻数据
onMounted(() => {
  (getNewsList().then((res) => {
    newsList.value = res.data?.list.map((item) => ({
      id: item.id,
      newsTitle: item.newsTitle,
      classReal: item.classReal,
      abstractReal: item.abstractReal,
      newsSource: item.newsSource,
      opPerson: item.opPerson,
      siteName: item.siteName,
      coverImage: item.coverImage,
      createTime: item.createTime,
      pubTime: item.pubTime,
      isPublished: item.isPublished,
      markContent: item.markContent,
    }))
    // 计算分组新闻列表
    calculateGroupedNewsList()
  }),
    newsIssueTemplate().then((res) => {
      console.log(res)
      newsTemplate.value = res.data.template
      publishForm.issueTitle = res.data.template
    }))
})

// 发布设置数据
const publishForm = reactive({
  issueTitle: '',
  pubway: 'imediate', // 默认立即发布
  waitPubTime: '',
  issueCoverImage: '',
  issueDescription: '',
  issuePublisher: user.username,
})

// 表单验证规则已移至表单项中

// 存储新闻发布模板
const newsTemplate = ref('')

// 表单引用
const publishFormRef = ref(null)

watch(
  () => publishForm.imgUrl,
  (n) => {
    console.log('url change', n)
  },
)

// 新闻详情相关变量
const currentNews = ref(null)
const showDetail = ref(false)

// 处理下一步按钮点击事件
const handleNextStep = () => {
  // 使用存储的模板作为默认值
  if (newsTemplate.value) {
    publishForm.issueTitle = newsTemplate.value
  }
  currentStep.value = 2
}

// 处理上一步按钮点击事件
const handlePrevStep = () => {
  currentStep.value = 1
}

// 处理确认发布事件
const handlePublish = (formEl) => {
  if (!formEl) return

  formEl.validate((valid) => {
    if (valid) {
      const { issueTitle, pubway, waitPubTime, issueCoverImage, issueDescription, issuePublisher } =
        publishForm
      
      // 如果是定时发布，但没有设置时间，则提示错误
      if (pubway === 'wait' && !waitPubTime) {
        ElMessage.error('请选择发布时间')
        return
      }
      
      newsPublishApi({
        issueTitle,
        pubway,
        waitPubTime: pubway === 'wait' ? waitPubTime : undefined,
        issueCoverImage,
        issueDescription,
        issuePublisher,
      }).then((res) => {
        if (res.code === 200) {
          ElMessage.success('新闻发布成功')
          console.log(res);
          
          router.push('/pool')
        }
      })
    } else {
      ElMessage.error('请填写必填项后再提交')
      return false
    }
  })
}

//点击新闻池跳转
const gotoPools = () => {
  router.push('/pool')
}

// 新闻详情
const handleNewsClick = (news) => {
  currentNews.value = news
  showDetail.value = true
}

// 从待发布列表中移除新闻
const removeFromPending = async (news) => {
  try {
    // 调用API更新新闻状态，将isSelect设置为0
    const res = await updateNews({ id: news.id, isSelect: 0 })

    if (res.code === 200) {
      // 从newsList中移除该新闻
      newsList.value = newsList.value.filter((item) => item.id !== news.id)
      // 重新计算分组列表
      calculateGroupedNewsList()
      ElMessage.success('已从待发布新闻移除')
    } else {
      ElMessage.error('移除失败，请重试')
    }
  } catch (error) {
    ElMessage.error('移除失败，请重试')
  }
}

// 获取分类标签样式
const getClassLabel = (value) => {
  const classItem = classList.find((item) => item.value === Number(value))
  return classItem ? classItem.label : value
}
// 根据分类值获取分类颜色
const getClassColor = (value) => {
  const classItem = classList.find((item) => item.value === Number(value))
  return classItem ? classItem.color : '#909399'
}

// 计算分组新闻列表
const calculateGroupedNewsList = () => {
  // 按分类分组
  const classMap = {}

  newsList.value.forEach((item) => {
    const classValue = item.classReal
    const classLabel = getClassLabel(classValue)

    if (classLabel) {
      if (!classMap[classValue]) {
        classMap[classValue] = {
          classValue: classValue,
          classLabel: classLabel,
          newsList: [],
        }
      }
      classMap[classValue].newsList.push(item)
    }
  })

  // 对每个分组内的新闻按ID排序(从小到大)
  Object.keys(classMap).forEach((key) => {
    classMap[key].newsList.sort((a, b) => {
      return a.id - b.id
    })
  })

  // 转换为数组格式
  groupedNewsList.value = Object.values(classMap)
  console.log(groupedNewsList.value)
}

// 上移新闻
const moveNewsUp = (groupIndex, newsIndex) => {
  if (newsIndex <= 0) return // 第一条新闻，禁用上箭头

  const group = groupedNewsList.value[groupIndex]
  const newsList = group.newsList

  // 交换位置
  const temp = newsList[newsIndex]
  newsList[newsIndex] = newsList[newsIndex - 1]
  newsList[newsIndex - 1] = temp

  // 生成正确的ordered数据结构
  const ordered = [
    {
      list: newsList.map((news, index) => ({
        id: news.id,
        orderNews: index,
      })),
    },
  ]

  orderNews(ordered).then((res) => {
    console.log(res)
    ElMessage.success('新闻顺序更新成功')
  })

  // 更新newsList
  updateNewsList()
}

// 下移新闻
const moveNewsDown = (groupIndex, newsIndex) => {
  const group = groupedNewsList.value[groupIndex]
  const newsList = group.newsList

  if (newsIndex >= newsList.length - 1) return // 最后一条，禁用下箭头

  // 交换位置
  const temp = newsList[newsIndex]
  newsList[newsIndex] = newsList[newsIndex + 1]
  newsList[newsIndex + 1] = temp

  const ordered = [
    {
      list: newsList.map((news, index) => ({
        id: news.id,
        orderNews: index,
      })),
    },
  ]

  orderNews(ordered).then((res) => {
    console.log(res)
    ElMessage.success('新闻顺序更新成功')
  })
  // 更新newsList
  updateNewsList()
}

// 更新newsList
const updateNewsList = () => {
  // 将分组后的新闻重新合并为newsList
  const updatedNewsList = []
  groupedNewsList.value.forEach((group) => {
    updatedNewsList.push(...group.newsList)
  })
  newsList.value = updatedNewsList
}

// 禁用当天之前的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now()
}
</script>

<template>
  <!-- 有数据时显示main-content -->
  <div class="main-content" v-if="newsList.length > 0">
    <div class="header">
      <div class="flex items-center">
        <span class="ball" :class="{ active: currentStep === 1 }">1</span>
        <span>发布内容</span>
      </div>
      <div class="flex items-center">
        <span class="ball" :class="{ active: currentStep === 2 }">2</span>
        <span>发布设置</span>
      </div>
    </div>

    <div class="news-list-container" v-if="currentStep === 1">
      <div class="class-group-container" v-if="newsList.length > 0">
        <div
          class="class-group"
          v-for="(group, groupIndex) in groupedNewsList"
          :key="group.classValue"
        >
          <div class="class-header">
            <span class="class-name">{{ group.classLabel }}</span>
            <span class="class-count">({{ group.newsList.length }})</span>
          </div>
          <div class="news-content-wrapper">
            <div
              class="news-content"
              v-for="(news, newsIndex) in group.newsList"
              :key="news.id"
              @click="handleNewsClick(news)"
            >
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <span
                    class="title-color"
                    :style="{ backgroundColor: getClassColor(news.classReal), color: '#fff' }"
                    >{{ getClassLabel(news.classReal) }}</span
                  >
                  <h4 style="font-weight: bold; cursor: pointer">
                    {{ news.newsTitle }}
                  </h4>
                </div>
                <div class="arrow-container">
                  <span
                    @click.stop="moveNewsUp(groupIndex, newsIndex)"
                    :class="{ disabled: newsIndex === 0 }"
                  >
                    <img src="../../assets//circle-arrow.svg" />
                  </span>
                  <span
                    class="arrow-flip"
                    @click.stop="moveNewsDown(groupIndex, newsIndex)"
                    :class="{ disabled: newsIndex === group.newsList.length - 1 }"
                  >
                    <img src="../../assets//circle-arrow.svg" />
                  </span>
                </div>
              </div>
              <div class="content-middle">{{ news.abstractReal }}</div>
              <div class="content-footer flex justify-between">
                <div class="flex items-center">
                  <img :src="news.coverImage" v-if="news.coverImage" />
                  <span style="margin-right: 15px">{{ news.siteName }}</span>
                  <span style="color: #a8a8a8">{{ news.createTime }}</span>
                </div>
                <div class="flex items-center">
                  <span style="margin-right: 10px; color: #a8a8a8">{{
                    news.opPerson ? '由' + news.opPerson + '添加' : ''
                  }}</span>
                  <img src="../../assets/btn-remove.svg" />
                  <button style="cursor: pointer" @click.stop="removeFromPending(news)">
                    移除
                  </button>
                  <img src="../../assets/编辑.svg" style="margin: 0 5px" />
                  <button style="color: #068ad6; cursor: pointer">编辑</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 发布设置页面 -->
    <el-form
      ref="publishFormRef"
      class="publish-settings"
      v-if="currentStep === 2"
      :model="publishForm"
    >
      <div class="setting-item">
        <label>标题</label>
        <el-form-item prop="issueTitle">
          <el-input
            v-model="publishForm.issueTitle"
            style="width: 615px"
            maxlength="100"
            placeholder="请输入发布新闻的标题"
            show-word-limit
            type="text"
          />
        </el-form-item>
      </div>
      <div class="setting-item">
        <label>封面和摘要</label>
        <div class="flex">
          <el-form-item
            prop="issueCoverImage"
            :rules="[{ required: true, message: '请上传封面图片', trigger: ['change', 'blur'] }]"
          >
            <Upload v-model="publishForm.issueCoverImage" />
          </el-form-item>
          <el-form-item
            prop="issueDescription"
            :rules="[{ required: true, message: '请输入新闻摘要', trigger: 'blur' }]"
          >
            <el-input
              v-model="publishForm.issueDescription"
              style="width: 360px"
              placeholder="请输入新闻摘要"
              :rows="4"
              maxlength="200"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </div>
      </div>
      <div class="setting-item">
        <label>发送时间</label>
        <div class="m-2">
          <input type="radio" v-model="publishForm.pubway" value="imediate" /> 立即发送
          <input type="radio" v-model="publishForm.pubway" value="wait" class="ml-3" /> 定时发送
          <el-date-picker
            v-if="publishForm.pubway === 'wait'"
            prop="waitPubTime"
            type="datetime"
            placeholder="发布时间"
            :disabled-date="disabledDate"
            class="ml-3"
            v-model="publishForm.waitPubTime"
          />
        </div>
      </div>
      <div class="setting-actions">
        <button @click="handlePrevStep" class="prevbtn">上一步</button>
        <button @click.prevent="handlePublish(publishFormRef)" class="publishbtn">确认发布</button>
      </div>
    </el-form>

    <div class="footer" v-if="currentStep === 1">
      <button @click="handleNextStep" class="nextbtn">下一步</button>
    </div>
  </div>

  <!-- 没有数据时显示box -->
  <div class="box" v-if="newsList.length === 0">
    <div
      class="flex flex-col w-[400px] h-[120px] items-center absolute top-[65%] left-[50%] translate-x-[-50%]"
    >
      <div style="font-weight: bold; font-size: 20px">待发布内容为空</div>
      <span style="color: #9a9a9a; padding: 10px 0"
        >你还没有添加任何新闻,快去新闻池挑选合适的新闻吧</span
      >
      <button class="gopools" @click="gotoPools">前往新闻池</button>
    </div>
  </div>
</template>

<style scoped>
.main-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 60px;
  margin: 0 auto;
  max-width: 600px;
  flex-shrink: 0;
}

.ball {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 1px solid #b8b4b4;
  color: #b8b4b4;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}

.active {
  background-color: #158bd6;
  color: #fff;
  border: 0;
}

.news-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
  height: calc(100% - 120px);
}

.class-group-container {
  padding: 0 10%;
}

.news-content {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.title-color {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
  margin-right: 10px;
  font-size: 12px;
}

.content-middle {
  margin: 10px 0;
  color: #333;
  line-height: 1.5;
}

.content-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.content-footer img {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.addpublish {
  background-color: #158bd6;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 5px 10px;
  margin-right: 10px;
  cursor: pointer;
}

.box {
  position: relative;
  width: 100%;
  height: 100%;
  background: url('../../assets/404.svg') no-repeat center;
  background-size: 100% 100%;
}

.gopools {
  width: 100px;
  height: 35px;
  background-color: #158bd6;
  color: #fff;
  padding: 5px 10px;
  cursor: pointer;
}

.footer {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 60px;
  margin: 0 auto;
  max-width: 600px;
}

.nextbtn {
  width: 100px;
  height: 35px;
  background-color: #158bd6;
  border-radius: 5px;
  color: #fff;
  padding: 5px 10px;
  cursor: pointer;
}

.prevbtn {
  width: 100px;
  height: 35px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  border-radius: 5px;
  padding: 5px 10px;
  cursor: pointer;
  margin-right: 10px;
}

.publishbtn {
  width: 100px;
  height: 35px;
  background-color: #158bd6;
  border-radius: 5px;
  color: #fff;
  padding: 5px 10px;
  cursor: pointer;
}

.publish-settings {
  padding: 20px;
  margin: 0 auto;
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.setting-item {
  margin-bottom: 20px;
}

.setting-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.statistics-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.statistics-container h3 {
  margin-bottom: 15px;
  color: #333;
}

.class-header {
  padding: 12px 15px;
  display: flex;
  align-items: center;
}

.class-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-right: 8px;
}

.class-count {
  font-size: 14px;
  color: #909399;
}

.setting-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.arrow-container {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.arrow-container span {
  margin-right: 5px;
}

.arrow-container span:last-child {
  margin-right: 0;
}

.arrow-flip img {
  transform: rotate(180deg);
  cursor: pointer;
}

.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.disabled img {
  pointer-events: none;
}

.avatar-uploader .avatar {
  width: 200px;
  height: 85px;
  display: block;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 200px;
  height: 95px;
  margin-right: 15px;
  text-align: center;
  background-color: #eee;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
</style>
